﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Channels;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static LiWi.Shell;

namespace LiWiTools
{
    public partial class UserControlRoot : UserControl
    {
        Data IPName;
        /// <summary>
        /// 表格更新状态
        /// </summary>
        public bool _viewFlag=false;
        string filePath;
        string basText;
        public UserControlRoot( Data IP)
        {
            InitializeComponent();
            IPName = IP;
            //// 禁用空白行
            //View_Axis.AllowUserToAddRows = false;
            //View_Axis.ReadOnly = true;
        }

        protected override void OnAutoValidateChanged(EventArgs e)
        {
            base.OnAutoValidateChanged(e);
            ////启用此控件时
            //if (this.Enabled)
            //{
            //    //启动异步任务
            //    _ = AsyncUpdateWin();
            //}
        }

        public async Task AsyncUpdateWin()
        {
            # region 控制器信息
            await Task.Run(() =>
            {
                while (!ToolsForm.dataControl[IPName].readFlag)
                {
                    Thread.Sleep(100);
                }
                this.Invoke(new Action(() =>
                {

                    txt_ControlData.Text = $"[Controller Specification]\r\n" +
                        $"ControlName：{ToolsForm.dataControl[IPName].controlName}\r\n" +
                        $"ControlID：{ToolsForm.dataControl[IPName].controlID}\r\n" +
                        $"SoftWare：{ToolsForm.dataControl[IPName].softWare}\r\n" +
                        $"HardWare：{ToolsForm.dataControl[IPName].hardWare}\r\n" +
                        $"SoftVersion：{ToolsForm.dataControl[IPName].softVersion}\r\n" +
                        $"HardVersion：{ToolsForm.dataControl[IPName].hardVersion}\r\n" +
                        ToolsForm.dataControl[IPName].controlData.ToString();
                }));
            });
            #endregion
        }

        /// <summary>
        /// 更改tab界面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int numPatas = tabControl1.SelectedIndex;
            AsyncUpdateTabPates(numPatas);
        }

        /// <summary>
        /// 更新点击页面
        /// </summary>
        /// <param name="numPates">页面</param>
        /// <returns></returns>
        public async Task AsyncUpdateTabPates(int numPates)
        {
            switch (numPates)
            {
                case 0:
                    this.Invoke(new Action(() =>
                    {

                        txt_ControlData.Text = $"[Controller Specification]\r\n" +
                            $"ControlName：{ToolsForm.dataControl[IPName].controlName}\r\n" +
                            $"ControlID：{ToolsForm.dataControl[IPName].controlID}\r\n" +
                            $"SoftWare：{ToolsForm.dataControl[IPName].softWare}\r\n" +
                            $"HardWare：{ToolsForm.dataControl[IPName].hardWare}\r\n" +
                            $"SoftVersion：{ToolsForm.dataControl[IPName].softVersion}\r\n" +
                            $"HardVersion：{ToolsForm.dataControl[IPName].hardVersion}\r\n" +
                            ToolsForm.dataControl[IPName].controlData.ToString();

                    }));
                    break;
                case 1:
                    
                    //DataAxis da = new DataAxis();
                    //da.GetAxisData(IPName, ToolsForm.dataControl[IPName]);
                    //ToolsForm.dataAxis[IPName] = da;
                    this.Invoke(new Action(() =>
                    {
                        UpAxisInformation();
                        //禁用第一行第一列编辑
                        View_Axis.CellBeginEdit += DataGridView_CellBeginEdit;
                        //更改表格对应参数修改
                        View_Axis.CellValueChanged += DataGridView_CellValueChange;
                    }));
                    break;
                case 2:
                    UpdatePointView();
                    InteMoveInformation();

                    //点动按钮绑定
                    btnXAdd.MouseDown += (sender, e) =>{JOGSport(comSelectX.SelectedIndex,Convert.ToInt16(comAtypeX.Text),1); };
                    btnXAdd.MouseUp += (sender, e) => { PMC_Stop(IPName.handle); };
                    btnXRed.MouseDown += (sender, e) => { JOGSport(comSelectX.SelectedIndex, Convert.ToInt16(comAtypeX.Text), -1); };
                    btnXRed.MouseUp += (sender, e) => { PMC_Stop(IPName.handle); };
                    
                    btnYAdd.MouseDown += (sender, e) => { JOGSport(comSelectY.SelectedIndex, Convert.ToInt16(comAtypeY.Text), 1); };
                    btnYAdd.MouseUp += (sender, e) => { PMC_Stop(IPName.handle); };
                    btnYRed.MouseDown += (sender, e) => { JOGSport(comSelectY.SelectedIndex, Convert.ToInt16(comAtypeY.Text), -1); };
                    btnYRed.MouseUp += (sender, e) => { PMC_Stop(IPName.handle); };
                    
                    btnZAdd.MouseDown += (sender, e) => { JOGSport(comSelectZ.SelectedIndex, Convert.ToInt16(comAtypeZ.Text), 1); };
                    btnZAdd.MouseUp += (sender, e) => { PMC_Stop(IPName.handle); };
                    btnZRed.MouseDown += (sender, e) => { JOGSport(comSelectZ.SelectedIndex, Convert.ToInt16(comAtypeZ.Text), -1); };
                    btnZRed.MouseUp += (sender, e) => { PMC_Stop(IPName.handle); };

                    btnUAdd.MouseDown += (sender, e) => { JOGSport(comSelectU.SelectedIndex, Convert.ToInt16(comAtypeU.Text), 1); };
                    btnUAdd.MouseUp += (sender, e) => { PMC_Stop(IPName.handle); };
                    btnURed.MouseDown += (sender, e) => { JOGSport(comSelectU.SelectedIndex, Convert.ToInt16(comAtypeU.Text), -1); };
                    btnURed.MouseUp += (sender, e) => { PMC_Stop(IPName.handle); };

                    break;


            }

        }


        /// <summary>
        /// 轴参数页面
        /// </summary>
        public void UpAxisInformation()
        {
           
            //清空行列
            View_Axis.Columns.Clear();
            View_Axis.Rows.Clear();

            //View_Axis.Dock = DockStyle.Fill;
            //this.Controls.Add(View_Axis);

            View_Axis.Columns.Add("param", "参数");

            for (int i = 0; i < ToolsForm.dataControl[IPName].axisVirtuAxises; i++)
            {
                //添加轴列
                View_Axis.Columns.Add($"Axis{i}", $"Axis{i}");
            }
            //填充参数行
            string[] paramenters = new string[]
            {
                 "轴类型","脉冲当量","起始速度", "运行速度","加速度","减速度","快速减速度",
                "正向软限位", "负向软限位","原点IO","正限位IO","负限位IO","报警信息"
            };
            foreach (string param in paramenters)
            {
                int rowIndex = View_Axis.Rows.Add();
                View_Axis.Rows[rowIndex].Cells[0].Value = param;
            }

            for (int i = 0; i < ToolsForm.dataControl[IPName].axisMaxMotor; i++)
            {
                object[] value = { ToolsForm.dataAxis[IPName].axisType[i],ToolsForm.dataAxis[IPName].units[i],
                    ToolsForm.dataAxis[IPName].startSpeed[i], ToolsForm.dataAxis[IPName].runSpeed[i],ToolsForm.dataAxis[IPName].accel[i],
                    ToolsForm.dataAxis[IPName].decel[i],ToolsForm.dataAxis[IPName].fastDec[i], (double)ToolsForm.dataAxis[IPName].fsLimit[i],
                    (double)ToolsForm.dataAxis[IPName].rsLimit[i],ToolsForm.dataAxis[IPName].datumIO[i],ToolsForm.dataAxis[IPName].fwdIO[i],
                    ToolsForm.dataAxis[IPName].revIO[i],ToolsForm.dataAxis[IPName].errAxisMes[i]};
                //添加数据
                for (int j = 0; j < value.Length; j++)
                {
                    View_Axis.Rows[j].Cells[i + 1].Value = value[j].ToString();
                }
            }
            //禁用排列
            View_Axis.AllowUserToOrderColumns = false;
            foreach(DataGridViewColumn column in View_Axis.Columns)
            {
                column.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            _viewFlag = true;
        }

        /// <summary>
        /// 禁用行列编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGridView_CellBeginEdit( object sender, DataGridViewCellCancelEventArgs e)
        {
            if(e.ColumnIndex==0||e.RowIndex==12) e.Cancel = true;
        }

        //更改表格数据
        private void DataGridView_CellValueChange(object sender, DataGridViewCellEventArgs e)
        {
            //Task.Run(() =>
            //{
                DataGridView view = sender as DataGridView;
                //获取更改的单元格的行列索引
                int rowIndex = e.RowIndex;
                int columnIndex = e.ColumnIndex;
                if (rowIndex >= 0 && columnIndex > 0)
                {
                    //获取更改后的值
                    object newValue = view.Rows[rowIndex].Cells[columnIndex].Value;
                    columnIndex -= 1;
                    int a = 888;
                    try
                    {                        
                        switch (rowIndex)
                        {
                            case 0:     //轴类型
                                a = 0;
                                PMC_SetAtype(IPName.handle, columnIndex, Convert.ToInt32(newValue));
                            ToolsForm.dataAxis[IPName].axisType[columnIndex] = Convert.ToInt32(newValue);
                                break;
                            case 1:     //脉冲当量
                                a = 1;
                                PMC_SetUnits(IPName.handle, columnIndex, Convert.ToSingle(newValue));
                            ToolsForm.dataAxis[IPName].units[columnIndex] = Convert.ToSingle(newValue);
                                break;
                            case 2:     //开始速度
                                a = 2;
                                PMC_SetLspeed(IPName.handle, columnIndex, Convert.ToSingle(newValue));
                            ToolsForm.dataAxis[IPName].startSpeed[columnIndex] = Convert.ToSingle(newValue);
                                break;
                            case 3:     //速度
                                a = 3;
                                PMC_SetSpeed(IPName.handle, columnIndex, Convert.ToSingle(newValue));
                            ToolsForm.dataAxis[IPName].runSpeed[columnIndex] = Convert.ToSingle(newValue);
                                break;
                            case 4:     //加速度
                                a = 4;
                                PMC_SetAccel(IPName.handle, columnIndex, Convert.ToSingle(newValue));
                            ToolsForm.dataAxis[IPName].accel[columnIndex] = Convert.ToSingle(newValue);
                                break;
                            case 5:     //减速度
                                a = 5;
                                PMC_SetDecel(IPName.handle, columnIndex, Convert.ToSingle(newValue));
                            ToolsForm.dataAxis[IPName].decel[columnIndex] = Convert.ToSingle(newValue);
                                break;
                            case 6:     //快速减速度
                                a = 6;
                                PMC_SetFastDec(IPName.handle, columnIndex, Convert.ToSingle(newValue));
                            ToolsForm.dataAxis[IPName].fastDec[columnIndex] = Convert.ToSingle(newValue);
                                break;
                            case 7:     //正向软限位
                                a = 7;
                                PMC_SetFsLimit(IPName.handle, columnIndex, Convert.ToInt32(newValue));
                            ToolsForm.dataAxis[IPName].fsLimit[columnIndex] = Convert.ToSingle(newValue);
                                break;
                            case 8:     //负向软限位
                                a = 8;
                                PMC_SetRsLimit(IPName.handle, columnIndex, Convert.ToInt32(newValue));
                            ToolsForm.dataAxis[IPName].rsLimit[columnIndex] = Convert.ToSingle(newValue);
                                break;
                            case 9:     //原点
                                a = 9;
                                PMC_SetDatumIn(IPName.handle, columnIndex, Convert.ToInt32(newValue));
                            ToolsForm.dataAxis[IPName].datumIO[columnIndex] = Convert.ToInt32(newValue);
                                break;
                            case 10:   //正限位
                                a = 10;
                                PMC_SetFwdIn(IPName.handle, columnIndex, Convert.ToInt32(newValue));
                            ToolsForm.dataAxis[IPName].fwdIO[columnIndex] = Convert.ToInt32(newValue);
                                break;
                            case 11:    //负限位
                                a = 11;
                                PMC_SetRevIn(IPName.handle, columnIndex, Convert.ToInt32(newValue));
                            ToolsForm.dataAxis[IPName].revIO[columnIndex] = Convert.ToInt32(newValue);
                                break;

                        }
                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show(ex.Message);
                        MessageBox.Show($"{a}");
                    }
                }
            //});
        }


        /// <summary>
        /// 读取点位参数
        /// </summary>
        public struct RunData
        {
            public float xPos;
            public float yPos;
            public float zPos;
            public float rPos;
            public float spd;

        }
        /// <summary>
        /// 插补运动参数
        /// </summary>
        public void InteMoveInformation()
        {
            for (int i = 0; i < ToolsForm.dataControl[IPName].axisVirtuAxises; i++)
            {
                comSelectX.Items.Add($"AXIS{i}");
                comSelectY.Items.Add($"AXIS{i}");
                comSelectZ.Items.Add($"AXIS{i}");
                comSelectU.Items.Add($"AXIS{i}");
            }
            comSelectX.Text = "AXIS0";
            comSelectY.Text = "AXIS1";
            comSelectZ.Text = "AXIS2";
            comSelectU.Text = "AXIS3";
            numSpeed.Value = 100;
            numAccel.Value = 1000;
            numDecel.Value = 1000;
            numUnint.Value = 100;
        }

        private void button_start_Click(object sender, EventArgs e)
        {
            int[] axisList = { comSelectX.SelectedIndex, comSelectY.SelectedIndex, comSelectZ.SelectedIndex, comSelectU.SelectedIndex };
            int[] atype = { Convert.ToInt16(comAtypeX.Text), Convert.ToInt16(comAtypeY.Text), Convert.ToInt16(comAtypeZ.Text), Convert.ToInt16(comAtypeU.Text) };
            foreach (var item in axisList)
            {
                int enable = 0;
                PMC_SetAxisEnable(IPName.handle, item, 1);
            }

            PMC_Rapidstop(IPName.handle, 3);
            for (int i = 0;i<axisList.Length;i++)
            {
                PMC_SetSpeed(IPName.handle, axisList[i], (float)numSpeed.Value);
                PMC_SetAccel(IPName.handle, axisList[i], (float)numAccel.Value);
                PMC_SetDecel(IPName.handle, axisList[i], (float)numDecel.Value);
                PMC_SetUnits(IPName.handle, axisList[i], (float)numUnint.Value);
                PMC_SetAtype(IPName.handle, axisList[i], atype[i]);
                PMC_SetMerge(IPName.handle, axisList[i], Convert.ToInt16(checkBox_changeMerge.Checked));
                PMC_SetSpeedDyna(IPName.handle, axisList[i], Convert.ToInt16(checkBox_changeSpd.Checked));
            }
            int cmode = 0;
            if (checkBox_corner.Checked)
            {
                cmode += 2;
                PMC_SetDecelAngle(IPName.handle, 0, (float)((float)numericUpDownstartAngle.Value * Math.PI / 180.0));
                PMC_SetStopAngle(IPName.handle, 0, (float)((float)numericUpDownStopAngle.Value * Math.PI / 180.0));
            }
            if (checkBox_corner2.Checked)
            {
                cmode += 8;

                PMC_SetFullSpRadius(IPName.handle, 0, (float)numericUpDown_circR.Value);
            }
            if (checkBox_corner3.Checked)
            {
                cmode += 32;
                PMC_SetFullSpRadius(IPName.handle, 0, (float)numericUpDown_ChamfR.Value);
            }
            PMC_SetCornerMode(IPName.handle, 0, cmode);
            PMC_SetForceSpeed(IPName.handle, 0, (float)numericUpDownLsp.Value);
            //运动点

            RunData runData = new RunData();
            PMC_Trigger(IPName.handle);
            if (dataGridView_point.RowCount > 0)
            {
                Task.Factory.StartNew(() =>
                {
                    for (int i = 0; i < dataGridView_point.RowCount-1; i++)
                    {
                        runData.xPos = Convert.ToSingle(dataGridView_point.Rows[i].Cells[1].Value.ToString());
                        runData.yPos = Convert.ToSingle(dataGridView_point.Rows[i].Cells[2].Value.ToString());
                        runData.zPos = Convert.ToSingle(dataGridView_point.Rows[i].Cells[3].Value.ToString());
                        runData.rPos = Convert.ToSingle(dataGridView_point.Rows[i].Cells[4].Value.ToString());
                        runData.spd = Convert.ToSingle(dataGridView_point.Rows[i].Cells[5].Value.ToString());
                        move(runData, axisList);
                    }
                });
            }
        }

        public void move(RunData runData, int[] axisList)
        {
            var ret = 0;
            float[] destlist = new float[4];
            destlist[0] = runData.xPos;
            destlist[1] = runData.yPos;
            destlist[2] = runData.zPos;
            destlist[3] = runData.rPos;
            int remainBuffer = 0;

            while (remainBuffer > 0 && ret == 0)
            {
                ret = PMC_GetRemain_LineBuffer(IPName.handle, 0, ref remainBuffer);
            }
            // if (checkBox_changeSpd.Checked)
            ret = PMC_MovePara(IPName.handle, 0, "SPEED", 0, runData.spd);
            if (radrunMove1.Checked)           //相对
            {

                ret = PMC_Move(IPName.handle, 4, axisList, destlist);
                if (ret != 0)
                {
                    return;
                }
            }
            else if (radrunMove2.Checked)      //绝对
            {
                ret = PMC_MoveAbs(IPName.handle, 4, axisList, destlist);
                if (ret != 0)
                {
                    return;
                }
            }
        }

        /// <summary>
        /// 更新点位表
        /// </summary>
        private void UpdatePointView()
        {

            //清空行列
            dataGridView_point.Columns.Clear();
            dataGridView_point.Rows.Clear();

            //添加轴列
            dataGridView_point.Columns.Add("point", "点位");
            dataGridView_point.Columns.Add("X", "X");
            dataGridView_point.Columns.Add("Y", "Y");
            dataGridView_point.Columns.Add("Z", "Z");
            dataGridView_point.Columns.Add("U", "U");
            dataGridView_point.Columns.Add("SPEED", "速度");

            //object[] value = { dataGridView_point.RowCount, 0, 0, 0, 0, 100 };
            ////添加数据
            //for (int j = 0; j < value.Length; j++)
            //{
            //    dataGridView_point.Rows[0].Cells[j].Value = value[j];
            //}

        }

        /// <summary>
        /// 添加点位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string[] datas = new string[6];
            datas[0] = Convert.ToString(dataGridView_point.RowCount);
            datas[1] = Convert.ToString(0);
            datas[2] = Convert.ToString(0);
            datas[3] = Convert.ToString(0);
            datas[4] = Convert.ToString(0);
            datas[5] = Convert.ToString(100);
            dataGridView_point.Rows.Add(datas);
        }

        /// <summary>
        /// 点动
        /// </summary>
        /// <param name="iaxis">轴</param>
        /// <param name="atype">轴类型</param>
        /// <param name="mode">1正向，-1负向</param>
        public void JOGSport(int iaxis, int atype, int mode)
        {
            PMC_SetSpeed(IPName.handle, iaxis, (float)numSpeed.Value);
            PMC_SetAccel(IPName.handle, iaxis, (float)numAccel.Value);
            PMC_SetDecel(IPName.handle, iaxis, (float)numDecel.Value);
            PMC_SetUnits(IPName.handle, iaxis, (float)numUnint.Value);
            PMC_SetAtype(IPName.handle, iaxis, atype);

            int[] axisnum = { iaxis };
            PMC_Base(IPName.handle, 1, axisnum);
            PMC_Single_Vmove(IPName.handle, iaxis, mode);           //连续运动：1正向，-1负向
        }

        private void button_stop_Click(object sender, EventArgs e)
        {
            PMC_Rapidstop(IPName.handle, 3);
        }

        private void button_zero_Click(object sender, EventArgs e)
        {
            for (int i = 0; i< ToolsForm.dataControl[IPName].axisMaxMotor;i++)
            {
                PMC_SetDpos(IPName.handle, i, 0);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (IPName.handle != IntPtr.Zero)
            {
                if (_viewFlag)
                {
                    //轴参数更新
                    for (int i = 0; i < ToolsForm.dataControl[IPName].axisVirtuAxises; i++)
                    {
                        object[] value = { ToolsForm.dataAxis[IPName].axisType[i],ToolsForm.dataAxis[IPName].units[i],
                            ToolsForm.dataAxis[IPName].startSpeed[i], ToolsForm.dataAxis[IPName].runSpeed[i],
                            ToolsForm.dataAxis[IPName].accel[i],ToolsForm.dataAxis[IPName].decel[i],ToolsForm.dataAxis[IPName].fastDec[i],
                            (double)ToolsForm.dataAxis[IPName].fsLimit[i],(double)ToolsForm.dataAxis[IPName].rsLimit[i],
                            ToolsForm.dataAxis[IPName].datumIO[i],ToolsForm.dataAxis[IPName].fwdIO[i],ToolsForm.dataAxis[IPName].revIO[i],
                            ToolsForm.dataAxis[IPName].errAxisMes[i]};
                        //添加数据
                        for (int j = 0; j < value.Length; j++)
                        {
                            View_Axis.Rows[j].Cells[i + 1].Value = value[j].ToString();
                        }
                    }
                }

               
            }
        }

        /// <summary>
        /// 下载BAS到控制器
        /// </summary>
        /// <param name="mode">0：RAM，1：ROM</param>
        private void DowmBAS(uint mode)
        {
            int a = PMC_BasDown(IPName.handle, filePath, mode);
            if (a == 0)  MessageBox.Show("下载成功");               
            else MessageBox.Show("下载失败！！！");
        }

        private void btn_OpenBas_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "选择BAS文件";
            openFileDialog.Filter = "BAS文件(*.BAS)|*.BAS|所有文件(*.*)|*.*";
            openFileDialog.InitialDirectory=Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            if(openFileDialog.ShowDialog() == DialogResult.OK)
            {
                filePath=openFileDialog.FileName;
                lab_filePath.Text = "路径："+ filePath;
                basText=File.ReadAllText(filePath);
                txt_BasText.Text = basText;
            }
        }



        private void btn_RAM_Click(object sender, EventArgs e)
        {
            DowmBAS(0);
        }

        private void btn_ROM_Click(object sender, EventArgs e)
        {
            DowmBAS(1);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            int a = PMC_Pause(IPName.handle);
            if (a == 0) MessageBox.Show("已暂停");
            else MessageBox.Show("暂停失败！！！");
        }

        private void btn_BASResume_Click(object sender, EventArgs e)
        {
            int a = PMC_Resume(IPName.handle);
            if (a == 0) MessageBox.Show("已继续运行");
            else MessageBox.Show("继续运行失败！！！");
        }

        private void btn_BASStop_Click(object sender, EventArgs e)
        {
            int a = PMC_Stop(IPName.handle);
            if (a == 0) MessageBox.Show("已停止");
            else MessageBox.Show("停止失败！！！");
        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            if (txt_BasText.Text == "") { MessageBox.Show("保存失败：文本为空"); return; }
            if (filePath==null)
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Title = "保存 .BAS 文件";
                saveFileDialog.DefaultExt = "bas";
                saveFileDialog.Filter = "Basic文件(*.bas)|*.bas|所有文件(*.*)|*.*";
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        filePath = saveFileDialog.FileName;
                        File.WriteAllText(filePath, txt_BasText.Text, Encoding.ASCII);
                        MessageBox.Show("保存成功");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("保存失败：" + ex.Message);
                    }
                }
                return;
            }
            try
            {
                File.WriteAllText(filePath, txt_BasText.Text);
                MessageBox.Show("保存成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存失败："+ex.Message);
            }
        }

        private void btn_SaveOther_Click(object sender, EventArgs e)
        {
            if (txt_BasText.Text == null) { MessageBox.Show("保存失败：文本为空"); return; }
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "保存 .BAS 文件";
            saveFileDialog.DefaultExt = "bas";
            saveFileDialog.Filter = "Basic文件(*.bas)|*.bas|所有文件(*.*)|*.*";
            if(saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    string fileOther = saveFileDialog.FileName;
                    File.WriteAllText(fileOther, txt_BasText.Text, Encoding.ASCII);
                    MessageBox.Show("保存成功");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("保存失败：" + ex.Message);
                }
            }
                
        }


    }
}
